<template>
  <!-- 新增见证事项-表单 -->
  <div>
    <div class="ui-mt20 ui-mr10">
      <!-- <pre>{{ JSON.stringify(topTaskAllData, null, 4) }}</pre> -->
      <!-- {{ cid }} -->
      <template v-for="itemA in topTaskAllData">
        <!-- <div>{{ key }}</div> -->
        <!-- {{ taskActive }} -->
        <!-- {{ itemA }} key === taskActive &&-->
        <template v-for="itemB in itemA">
          <el-form
            :key="'addform_' + matterType + itemB.witnessSubTaskId"
            :ref="'addform_' + matterType + itemB.witnessSubTaskId"
            v-show="itemB.witnessSubTaskId === cid"
            grid
            :model="addformObj[matterType + itemB.witnessSubTaskId]"
            :rules="rules"
            label-width="90px"
            :inline="false"
            size="normal"
          >
            <!-- {{ addformObj[matterType+itemB.witnessSubTaskId] }}
            {{ taskActive }} {{ cid }} {{ itemB.witnessSubTaskId }} prop="witnessScene"-->
            <el-form-item v-if="matterType === 'add'" :span="24" label="见证场景" required>
              <el-select
                style="width: 100%"
                v-model="addformObj[matterType + itemB.witnessSubTaskId].witnessScene"
                placeholder="请选择"
                @change="witnessSceneChangeFn"
              >
                <el-option
                  v-for="item in witnessSceneOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="matterType === 'add' && addformObj[matterType + itemB.witnessSubTaskId].witnessScene === 'PEOPLE'"  :span="24" label="是否按项目添加" >
              <el-switch
                v-model="addformObj[matterType + itemB.witnessSubTaskId].isProject"
                @change="isProjectChange"
                active-color="#1890ff">
              </el-switch>
            </el-form-item>

            <el-form-item :span="12" label="见证事项" required prop="taskMatterCode">
              <!-- {{ witnessMatterOptions }} -->
              <!-- {{ addformObj[matterType+itemB.witnessSubTaskId].taskMatterCode }} -->
              <el-cascader
                v-model="addformObj[matterType + itemB.witnessSubTaskId].taskMatterCode"
                style="width: 100%"
                option-max-width="300px"
                :options="witnessMatterOptions"
                @change="taskMattterCodeChangeFn"
                @focus="matterFocusFn"
              />
              <span class="witness-matter-warning" v-if="alertMatterFlag">
                暂未配置，请联系管理员在【系统管理-见证事项管理】中添加
              </span>
            </el-form-item>
            <el-form-item :span="12" label="状态" prop="status">
              <i style="color: #e82f2f; position: relative; right: 48px">*</i>
              <el-radio-group
                v-model="addformObj[matterType + itemB.witnessSubTaskId].matterStatus"
                @change="matterStatusChangeFn"
              >
                <el-radio label="NORMAL_TYPE">正常</el-radio>
                <el-radio label="EXCEPTION_TYPE">异常</el-radio>
              </el-radio-group>
              <!-- 暂时隐藏预警级别 22-3-25 -->
              <!-- <el-cascader
            v-model="addformObj[matterType+itemB.witnessSubTaskId].warningLevel"
            style="margin-left: 10px"
            placeholder="选择等级"
            option-max-width="150px"
            class="ui-w120"
            :options="initData.recordExceStatusEnum"
            :disabled="addformObj[matterType+itemB.witnessSubTaskId].matterStatus === 'NORMAL_TYPE'"
            @change="handleErrorLevelChangeFn"
          /> -->
            </el-form-item>
            <!-- {{ matterInstruction }} -->
            <!-- {{ addformObj[matterType+itemB.witnessSubTaskId].itemCodeList }} -->
            <el-form-item :span="matterType === 'add' ? 12 : 24" label="事项说明" prop="itemCodeList">
              <el-cascader
                v-model="addformObj[matterType + itemB.witnessSubTaskId].itemCodeList"
                style="width: 100%"
                option-max-width="300px"
                :props="{ multiple: false }"
                :options="matterInstruction"
                @change="itemColeListChangeFn"
              />
            </el-form-item>
            <el-form-item label="发生时间" v-if="matterType === 'add'" prop="occurrentTime" :span="12">
              <el-date-picker
                v-model="addformObj[matterType + itemB.witnessSubTaskId].occurrentTime"
                style="width: 100%"
                unlink-panels
                type="datetime"
                :clearable="true"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                @click-now="witnessItemRuleGetTimeFn"
              />
            </el-form-item>
            <el-form-item label="附件信息" :span="24">
              <el-upload
                :key="'fireUploadDialog_' + itemB.witnessSubTaskId"
                :ref="'fireUploadDialog_' + itemB.witnessSubTaskId"
                class="fire-upload-dialog"
                action=""
                :limit="10"
                :on-exceed="handleExceed"
                :before-remove="beforeRemoveFn"
                :before-upload="beforeUploadImage"
                :on-remove="onRemoveFn"
                accept=".pdf,.jpg,.png,.jpeg,.gif"
                :http-request="uploadFileFn"
                :on-success="onUploadSuccessFn"
                :on-error="onUploadFailedFn"
              >
                <el-button size="small" icon="el-icon-plus" type="primary" style="width: 100%" dashed>
                  点击上传
                </el-button>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="见证记录"
              prop="witnessRecordDesc"
              :rules="{ required: true, message: '见证记录不能为空', trigger: 'blur' }"
              :span="24"
            >
              <el-input
                v-model.trim="addformObj[matterType + itemB.witnessSubTaskId].witnessRecordDesc"
                type="textarea"
                style="width: 100%"
                :rows="4"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </template>
      </template>
    </div>
  </div>
</template>
<script>
  import {
    subtaskReview,
    witnessRecordAdd,
    stopWitness,
    recoverWitness,
    itemDictList,
    uploadFile,
    witnessRecordList,
    witnessItemRuleGetTime
  } from "../../api/api";
  export default {
    name: "WorkBenchAddForm",
    components: {},
    props: {
      matterType: {
        type: String,
        default: "add"
      },
      initData: {
        type: Object,
        default() {
          return {};
        }
      },
      currData: {
        type: Object,
        default() {
          return {};
        }
      },
      topTaskActive: {
        type: String,
        default: ""
      },
      show: {
        type: Boolean,
        default: false
      },
      taskActive: {
        type: String,
        default: ""
      },
      cid: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        dialogTitle: "新增见证事项",
        id: "",
        addformObj: {},
        topTaskAllData: {},
        currProjectData: {},
        matterInstruction: [],
        pickerOptions: {
          disabledDate(time) {
            console.log("time", time);
            return false; // time.getTime() < Date.now();
          }
        },
        witnessMatterOptions: [],
        witnessSceneOptions: [],
        alertMatterFlag: false,
        BaseInfoVisible: false,
        loading: false,
        visible: false,
        cardVisible: true,
        taskFormCache: {}, // 所有任务的表单缓存
        addform: {
          isProject:false,
          matterStatus: "NORMAL_TYPE",
          taskMatterCode: [],
          itemCodeList: [],
          witnessRecordDesc: "",
          occurrentTime: "",
          warningLevel: "",
          attachmentList: []
        },
        rules: {
          witnessScene: [{ required: true, message: "见证场景不能为空", trigger: ["change", "blur"] }],
          taskMatterCode: [{ required: true, message: "见证事项不能为空", trigger: ["change", "blur"] }],
          itemCodeList: [{ required: true, message: "事项说明不能为空", trigger: ["change", "blur"] }],
          occurrentTime: [{ required: true, message: "发生时间不能为空", trigger: "blur" }],
          witnessRecordDesc: [
            {
              required: true,
              message: "见证记录不能为空",
              trigger: ["change", "blur"]
            }
          ]
          // 预警级别校验暂时隐藏
          // status: [
          //   {
          //     message: "选择等级不能为空",
          //     validator: (rule, value, callback) => {
          //       console.log(value);
          //       if (this.addform.matterStatus !== "NORMAL_TYPE" && !this.addform.warningLevel) {
          //         callback(new Error("选择等级不能为空"));
          //       } else {
          //         callback();
          //       }
          //     },
          //     trigger: "blur"
          //   }
          // ]
          // keyWord: [{ required: true, message: "key不能为空", trigger: "blur" }],
        }
      };
    },
    computed: {
      // visible() {
      //   return this.show;
      // },
      allTaskData() {
        return this.$store.getters.topTaskAllData;
      }
    },
    watch: {
      cid: {
        handler(newVal) {
          console.log("cid", newVal);
          if (newVal) {
            this.initDataFn(newVal);
          }
        },
        immediate: true
      },
      allTaskData: {
        handler(data) {
          // this.topTaskYujingData
          this.witnessSceneOptions = this.initData.witnessScene;
          console.log("formallTaskData", data);
          this.addformObj = {};
          Object.keys(data).forEach((key) => {
            data[key].forEach((itemB) => {
              if (!this.addformObj[this.matterType + itemB.witnessSubTaskId]) {
                this.$set(
                  this.addformObj,
                  this.matterType + itemB.witnessSubTaskId,
                  JSON.parse(JSON.stringify(this.addform))
                );
              }
              // this.addformObj[matterType+itemB.witnessSubTaskId] = JSON.parse(JSON.stringify(this.addform));
            });
          });
          this.$set(this, "topTaskAllData", data);
          // this.witnessItemRuleGetTimeFn();
          // setTimeout(() => {
          //   this.initFromFn();
          // }, 100);
          this.initDataFn(this.cid);
        },
        immediate: true
      }
      // TODO 这里不更新
      // taskActive(val) {
      //   console.log("taskActive", val);
      // },
      // show(val) {
      //   this.visible = val;
      //   this.detailData = [];
      //   console.log("show", val);
      //   // this.matterType = "add";
      //   if (val) {
      //     this.id = this.$route.query.id;
      //     // if (this.matterType === "STOP") {
      //     //   this.dialogTitle = "新增暂停事项";
      //     // }
      //     // if (this.matterType === "RECOVER") {
      //     //   this.dialogTitle = "新增恢复事项";
      //     // }
      //     // if (this.matterType === "add") {
      //     //   this.dialogTitle = "新增见证事项";
      //     // }
      //     this.currProjectData = this.currData;
      //     this.initFn();
      //   }
      // }
    },
    methods: {
      //是否按项目添加修改事件
      isProjectChange(isProject){
        this.$emit('isProjectChange',isProject)
      },

      async initFn() {
        console.log("forminitFn");
        if (this.initFlag) {
          return;
        }
        this.initFlag = setTimeout(() => {
          clearTimeout(this.initFlag);
          this.initFlag = null;
        }, 300);
        this.witnessSceneChangeFn("PEOPLE", "init");
        // this.initFromFn("init");
        // await this.witnessRecordListAllFn();
        // await this.initParentCodeFn();
      },
      // 见证记录-所有-添加时的禁用属性
      async witnessRecordListAllFn(msg) {
        console.log("msg", msg);
        if (!this.id) {
          return;
        }
        const p = {
          witnessSubTaskId: this.id,
          pageSize: -1
        };
        this.recordDataAll = [];
        console.log("witnessRecordListAllFn", this.id);
        try {
          const res = await witnessRecordList(p);
          if (res.success) {
            this.recordDataAll = res.data.result;
          }
        } catch (error) {
          console.error(error);
        }
      },
      // 见证记录-所有-添加时的禁用属性
      async witnessItemRuleGetTimeFn() {
        const p = {};
        console.log("this.id", this.id);
        try {
          const res = await witnessItemRuleGetTime(p);
          console.log("res_time", res);
          if (res.success) {
            this.addformObj[this.matterType + this.cid].occurrentTime = res.data;
            // return res.data;
          }
        } catch (error) {
          console.error(error);
        }
      },
      matterStatusChangeFn() {
        this.addformObj[this.matterType + this.cid].witnessRecordDesc=""
        if (this.addformObj[this.matterType + this.cid].matterStatus === "NORMAL_TYPE") {
          this.addformObj[this.matterType + this.cid].warningLevel = "";
        }
        this.taskMattterCodeChangeFn();
      },
      itemColeListChangeFn(val) {
        console.log("val", val);
        console.log("this.matterInstruction", this.matterInstruction);
        // const obj = this.matterInstruction.find((itemC) => itemC.defaultItem === "DEFAULT");
        const obj = this.matterInstruction.find((item) => item.value === val[0]);
        this.addformObj[this.matterType + this.cid].witnessRecordDesc = obj.record;
        this.$refs[`addform_${this.matterType}${this.cid}`] &&
          this.$refs[`addform_${this.matterType}${this.cid}`][0].clearValidate();
      },
      async taskMattterCodeChangeFn() {
        console.log("taskMattterCodeChangeFn");
        // TODO 这里要判断见证场景：人工见证事项支持多次选择
        // 预警级别逻辑暂时注释
        // if (this.addform.matterStatus === "NORMAL_TYPE") {
        //   this.$refs.addform.validateField("status");
        // }
        this.addformObj[this.matterType + this.cid].itemCodeList = [];
        // console.log("this.addform.taskMatterCode", this.addform.taskMatterCode);
        if (
          this.addformObj[this.matterType + this.cid].taskMatterCode.length > 0 &&
          this.addformObj[this.matterType + this.cid].taskMatterCode[0]
        ) {
          // this.$refs["addform"].resetFields();
          const p = {
            parentCode: this.addformObj[this.matterType + this.cid].taskMatterCode[0] || -1,
            itemStatus: this.addformObj[this.matterType + this.cid].matterStatus
          };
          // if (p.parentCode !=== -1) {
          // p.itemStatus = this.addform.matterStatus;
          // }
          this.matterInstruction = await this.itemDictListFn(p);
          // console.log("this.matterInstruction", this.matterInstruction);
          // console.log("this.addform.itemCodeList", this.addformObj[this.matterType+this.cid].itemCodeList);
          if (this.matterInstruction && this.matterInstruction[0]) {
            let arr = this.matterInstruction.find((item) => item.defaultItem === "DEFAULT");
            console.log("arr", arr); // 数据没有默认
            if (!arr) {
              arr = {};
            }
            if (
              !this.addformObj[this.matterType + this.cid].itemCodeList ||
              !this.addformObj[this.matterType + this.cid].itemCodeList.length
            ) {
              this.$set(this.addformObj[this.matterType + this.cid], "itemCodeList", [arr.value]);
            }
            // this.addformObj[this.matterType+this.cid].itemCodeList = [arr.value];
            if (!this.addformObj[this.matterType + this.cid].witnessRecordDesc) {
              this.addformObj[this.matterType + this.cid].witnessRecordDesc = arr.record;
            }
          }
        }
      },
      // 见证场景
      async witnessSceneChangeFn(e, flag) {
        console.log("aaaaa", flag);
        console.log("witnessSceneChange", e);
        // this.taskMattterCodeChangeFn();
        if (!flag) {
          this.initFromFn("witnessSceneChange");
        }
        this.addformObj[this.matterType + this.cid].witnessScene = e;
        await this.matterFocusFn();
      },
      async matterFocusFn(flag) {
        console.log("matterFocusFn");
        console.log("witnessMatterOptions");
        // if (flag === "init") {
        // }
        // FIXME 人工
        if (this.addformObj[this.matterType + this.cid].witnessScene !== "PEOPLE") {
          await this.witnessRecordListAllFn("matterFocusFn");
        }
        await this.initParentCodeFn(flag);
      },
      //  限制上传图片格式
      beforeUploadImage(file) {
        console.log("file.szie", file.size);
        console.log("file.type", file.type);
        const isSize = file.size / 1024 / 1024; // 文件大小
        const fileSize = 5;
        if (isSize > fileSize) {
          this.uploadFlag = true;
          // this.$message.error(`上传图片大小不能超过${fileSize}MB!`);
          this.$msgbox({
            title: "提示",
            message: `文件大小不能超过${fileSize}MB，请重新上传。`,
            type: "warning"
          });
          return false;
        }
        return true;
      },
      // 文件相关
      beforeRemoveFn(file) {
        if (!this.uploadFlag) {
          return this.$confirm(`确定移除 ${file.name}？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          });
        }
      },
      onRemoveFn(file) {
        for (const [index, item] of this.addformObj[this.matterType + this.cid].attachmentList.entries()) {
          if (item.uid === file.uid) {
            this.addformObj[this.matterType + this.cid].attachmentList.splice(index, 1);
            return;
          }
        }
      },
      async uploadFileFn(params) {
        try {
          const form = new FormData();
          form.append("file", params.file);
          const res = await uploadFile(form);
          if (res.success) {
            this.addformObj[this.matterType + this.cid].attachmentList.push({
              ...params.file,
              attachId: res.data
            });
          }
        } catch (error) {
          console.error(error);
          this.$message({
            type: "error",
            message: "上传文件失败，请稍后再试",
            single: true
          });
        }
      },
      onUploadSuccessFn() {
        this.$message({
          type: "success",
          message: "上传文件成功!",
          single: true
        });
      },
      handleExceed() {
        // files, fileList
        this.$message.warning(`当前限制最多上传 10 个文件`);
      },
      onUploadFailedFn() {
        this.$message({
          type: "error",
          message: "上传文件失败，请稍后再试",
          single: true
        });
      },
      handleErrorLevelChangeFn() {
        this.$refs.addform.validateField("status");
      },
      handleClickAddFn() {
        document.getElementsByClassName("el-upload__input")[0].click();
      },
      addMattersSubmitFn(e) {
        console.log("e", e);
      },
      async initDataFn(newVal) {
        // clearTimeout(this.initFlag);
        // this.initFlag = setTimeout(async () => {
        //   this.initFlag = null;
        console.log("initData", newVal);
        this.id = newVal;
        if (newVal) {
          console.log("this.addformObj[newVal]", this.addformObj[this.matterType + newVal]);
          if (this.addformObj[this.matterType + newVal]) {
            if (this.addformObj[this.matterType + newVal] && !this.addformObj[this.matterType + newVal].occurrentTime) {
              this.witnessItemRuleGetTimeFn();
            }
            if (!this.addformObj[this.matterType + newVal].witnessScene) {
              this.addformObj[this.matterType + newVal].witnessScene = "PEOPLE";
            }
          } else {
            console.log("initData33333");
            await this.initFromFn(this.id);
          }
          // TODO SSR 需要更新见证事项、事项说明下拉菜单
          if (!this.addformObj[this.matterType + this.cid].taskMatterCode) {
            console.log("initData33333卡卡",this.addformObj[this.matterType + this.cid].witnessScene);
            this.witnessSceneChangeFn(this.addformObj[this.matterType + this.cid].witnessScene, "allTaskData");
          } else {
            // 见证事项
            await this.witnessMatterOptionsFn();
            // 事项说明
            await this.matterInstructionFn();
            // this.witnessMatterOptions = await this.itemDictListFn(p);
            // witnessMatterOptions
          }
          // this.matterFocusFn("init");
          this.currProjectData = this.currData;
        }
        // }, 200);
      },
      async matterInstructionFn() {
        if (!this.addformObj[this.matterType + this.cid].taskMatterCode[0]) {
          this.matterInstruction =[]
          return;
        }
        const p = {
          parentCode: this.addformObj[this.matterType + this.cid].taskMatterCode[0] || -1,
          itemStatus: this.addformObj[this.matterType + this.cid].matterStatus
        };
        this.matterInstruction = await this.itemDictListFn(p);
        if (this.matterInstruction && this.matterInstruction[0]) {
          let arr = this.matterInstruction.find((item) => item.defaultItem === "DEFAULT");
          console.log("arr", arr); // 数据没有默认
          if (!arr) {
            arr = {};
          }
          if (
            !this.addformObj[this.matterType + this.cid].itemCodeList ||
            !this.addformObj[this.matterType + this.cid].itemCodeList.length
          ) {
            let arrValue = [];
            if (arr.value) {
              arrValue = [arr.value];
            }

            this.$set(this.addformObj[this.matterType + this.cid], "itemCodeList", arrValue);
          }
          // this.addformObj[this.matterType+this.cid].itemCodeList = [arr.value];
          if (!this.addformObj[this.matterType + this.cid].witnessRecordDesc) {
            this.addformObj[this.matterType + this.cid].witnessRecordDesc = arr.record;
          }
        }
      },
      async witnessMatterOptionsFn() {
        const p = { parentCode: -1 };
        if (this.matterType === "STOP") {
          p.witnessScene = "STOP";
        } else if (this.matterType === "RECOVER") {
          p.witnessScene = "RECOVER";
        } else {
          // p.witnessScene = "PEOPLE";
          p.witnessScene = this.addformObj[this.matterType + this.cid].witnessScene;
        }
        const arr = await this.itemDictListFn(p);
        /* 这里需要判断，添加、暂停、恢复 */
        if (
          this.matterType === "STOP" ||
          this.matterType === "RECOVER" ||
          this.addformObj[this.matterType + this.cid].witnessScene === "PEOPLE"
        ) {
          this.$set(this, "witnessMatterOptions", arr);
        } else {
          this.$set(this, "witnessMatterOptions", this.refreshOptionsFn(arr));
        }
        if (this.witnessMatterOptions && this.witnessMatterOptions.length === 1) {
          console.log(
            "this.addformObj[this.matterType+this.cid].taskMatterCode",
            this.addformObj[this.matterType + this.cid].taskMatterCode
          );
          if (
            !this.addformObj[this.matterType + this.cid].taskMatterCode ||
            !this.addformObj[this.matterType + this.cid].taskMatterCode.length
          ) {
            this.addformObj[this.matterType + this.cid].taskMatterCode = [this.witnessMatterOptions[0].value];
          }
          if (!this.addformObj[this.matterType + this.cid].witnessRecordDesc) {
            this.addformObj[this.matterType + this.cid].witnessRecordDesc = this.witnessMatterOptions[0].record;
          }
          // await this.taskMattterCodeChangeFn();
          // this.addform.itemCodeList = [this.matterInstruction[0].value];
        }
        // 如果为空提示显示
        this.alertMatterFlag = !this.witnessMatterOptions.length;
      },
      initFromFn(id) {
        console.log("id==========================", id);
        console.log("this.id=================", this.id);
        this.recordData = [];
        this.activities = [];
        this.sideRecordActive = "first";
        const fileRef = `fireUploadDialog_${this.id}`;
        this.$refs[fileRef] && this.$refs[fileRef][0].clearFiles();
        // this.pageObj.currentPage = 1;
        // this.pageQueryList.currentPage = 1;
        this.loading = false;
        this.submitLoading = false;
        // debugger;
        // console.log("this.id===", this.id);
        if (!this.addformObj[this.matterType + this.cid]) {
          return;
        }
        // 初始化 表单
        this.addformObj[this.matterType + this.cid].witnessScene = "PEOPLE";
        this.addformObj[this.matterType + this.cid].taskMatterCode = "";
        this.addformObj[this.matterType + this.cid].matterStatus = "NORMAL_TYPE";
        this.addformObj[this.matterType + this.cid].witnessRecordDesc = "";
        // TODO 这里要改服务器时间
        if (!this.addformObj[this.matterType + this.cid].occurrentTime) {
          this.witnessItemRuleGetTimeFn();
          //   //   this.addformObj[this.matterType+this.cid].occurrentTime = this.$moment(new Date()).format("yyyy-MM-DD HH:mm:ss");
        }
        this.addformObj[this.matterType + this.cid].itemCodeList = [];
        this.addformObj[this.matterType + this.cid].warningLevel = "";
        this.addformObj[this.matterType + this.cid].attachmentList = []; // 附件列表
        this.witnessMatterOptions = [];
        this.witnessSceneOptions = this.initData.witnessScene;
        this.matterInstruction = [];
        console.log("this.addformObj[this.matterType+this.cid]", this.addformObj[this.matterType + this.cid]);
        // this.$refs["addformObj[this.matterType+this.cid]"] && this.$refs["addformObj[this.matterType+this.cid]"].clearValidate();
        this.$refs[`addform_${this.id}`] && this.$refs[`addform_${this.id}`][0].resetFields();
      },
      async initParentCodeFn(msg) {
        console.log("initParentCodeFn=======", msg);
        // TODO 人工见证事项 -》获取 见证事项列表
        const p = { parentCode: -1 };
        if (this.matterType === "STOP") {
          p.witnessScene = "STOP";
        } else if (this.matterType === "RECOVER") {
          p.witnessScene = "RECOVER";
        } else {
          // p.witnessScene = "PEOPLE";
          p.witnessScene = this.addformObj[this.matterType + this.cid].witnessScene;
        }
        const arr = await this.itemDictListFn(p);
        /* 这里需要判断，添加、暂停、恢复 */
        if (
          this.matterType === "STOP" ||
          this.matterType === "RECOVER" ||
          this.addformObj[this.matterType + this.cid].witnessScene === "PEOPLE"
        ) {
          this.$set(this, "witnessMatterOptions", arr);
        } else {
          this.$set(this, "witnessMatterOptions", this.refreshOptionsFn(arr));
        }
        console.log("this.witnessMatterOptions", this.witnessMatterOptions);
        // console.log('');
        // 只有一个选项，作为默认选项 by link 20220702
        this.$nextTick(async () => {
          if (this.witnessMatterOptions && this.witnessMatterOptions.length === 1 && msg !== "init") {
            console.log(
              "this.addformObj[this.matterType+this.cid].taskMatterCode",
              this.addformObj[this.matterType + this.cid].taskMatterCode
            );
            if (
              !this.addformObj[this.matterType + this.cid].taskMatterCode ||
              !this.addformObj[this.matterType + this.cid].taskMatterCode.length
            ) {
              this.addformObj[this.matterType + this.cid].taskMatterCode = [this.witnessMatterOptions[0].value];
            }
            if (!this.addformObj[this.matterType + this.cid].witnessRecordDesc) {
              this.addformObj[this.matterType + this.cid].witnessRecordDesc = this.witnessMatterOptions[0].record;
            }
            await this.taskMattterCodeChangeFn();
            // this.addform.itemCodeList = [this.matterInstruction[0].value];
          }
        });
        // if (this.addformObj[this.matterType+this.cid].taskMatterCode) {
        // }
        // 如果为空提示显示
        this.alertMatterFlag = !this.witnessMatterOptions.length;
      },
      // 刷新见证事项的状态
      refreshOptionsFn(arr) {
        return arr.map((item) => {
          const flag = this.recordDataAll.some(
            (recordItem) =>
              // console.log(recordItem.data.parentItemCode, item.value);
              recordItem.data.parentItemCode === item.value
          );
          if (flag) {
            item.disabled = true;
          }
          return item;
        });
      },
      // 见证事项-列表
      async itemDictListFn(p = {}) {
        // let p = {
        //   parentCode: this.addform.taskMatterCode[0] || -1,
        // };
        // if (p.parentCode !== -1) {
        //   p.itemStatus = this.addform.matterStatus;
        // }
        console.log("this.cid====", this.cid);
        console.log("this.id====", this.id);
        if (!this.cid) {
          return;
        }
        p.witnessSubTaskId = this.cid;
        try {
          const res = await itemDictList(p);
          if (res.success) {
            this.itemDictListData = res.data.map((item) => ({
              label: item.itemName,
              value: item.itemCode,
              defaultItem: item.defaultItem,
              record: item.record
            }));
            return this.itemDictListData;
          }
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 父调用表单方法
      formValidateFn(flag) {
        console.log(`addform_${this.matterType}${this.cid}`);
        console.log("addform_", this.$refs[`addform_${this.matterType}${this.cid}`]);
        const ref = `addform_${this.matterType}${this.cid}`;
        this.$refs[ref][0].validate((valid) => {
          console.log("addform_v", valid);
          if (valid) {
            console.log("this.$parent", this.$parent);
            this.$parent.$parent.loading = true;
            // this.$parent.submitLoading = true;
            this.witnessRecordAddFn(flag);
          } else {
            return false;
          }
        });
      },
      // 见证事项-提交
      submitRecordFn(flag) {
        const ref = `addform_${this.matterType}${this.cid}`;
        this.$refs[ref].validate((valid) => {
          // this.$refs.addform.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.submitLoading = true;
            this.witnessRecordAddFn(flag);
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      // 见证事项-新增
      async witnessRecordAddFn(flag) {
        // dataStatus INVALID
        // 枚举值: INVALID,VALID,TEMP,DELETE,ARCHIVE
        // itemCode 见证事项编码
        // itemStatus NORMAL_TYPE
        // 见证事项状态 枚举值: NORMAL_TYPE,EXCEPTION_TYPE
        // source 见证记录来源
        // witnessRecordDesc 见证记录描述
        // witnessRecordTime 记录时间
        // witnessSubTaskId 见证子任务id
        // witnessTaskId
        let p = {};
        // if (params) {
        //   // 复核调新增
        //   p = params;
        // } else {
        const saveformData = this.addformObj[this.matterType + this.cid];
        const itemCodes = saveformData.itemCodeList.map((item) => item);
        if (this.matterType === "add") {
          saveformData.occurrentTime;
        }
        p = {
          itemCodes,
          itemStatus: saveformData.matterStatus,
          witnessRecordDesc: saveformData.witnessRecordDesc,
          occurrentTime: saveformData.occurrentTime,
          // 预警级别暂时写死 22-3-25
          warningLevel: this.matterStatus === "NORMAL_TYPE" ? "" : "HEIGHT",
          // warningLevel: this.matterStatus === "NORMAL_TYPE" ? "" : saveformData.warningLevel[0],
          attachmentList: saveformData.attachmentList.map((item) => item.attachId),
          witnessSubTaskId: this.currProjectData.witnessSubTaskId,
          witnessTaskId: this.currProjectData.witnessTaskId,
          source: this.$store.getters.username || localStorage.getItem("username")
        };
        // }
        try {
          let res = null;
          if (this.matterType === "STOP") {
            res = await stopWitness(p);
          } else if (this.matterType === "RECOVER") {
            res = await recoverWitness(p);
          } else {
            if (saveformData.isProject) {
              const { witnessLinkCode, projectCode} = this.currProjectData;
              const witnessSubTaskIdAll = this.allTaskData[witnessLinkCode].filter(item => item.projectCode === projectCode).map(item => item.witnessSubTaskId);
              p.extendData = JSON.stringify({
                witnessSubTaskIdAll:witnessSubTaskIdAll.join(',')
              })
            }
            res = await witnessRecordAdd(p);
          }
          if (res.success) {
            // this.addform.itemCodeList = [];
            // if (!params) {
            this.addformObj[this.matterType + this.cid].witnessRecordDesc = "";
            this.addformObj[this.matterType + this.cid].matterStatus = "NORMAL_TYPE";
            this.addformObj[this.matterType + this.cid].warningLevel = "";
            this.addformObj[this.matterType + this.cid].attachmentList = [];
            this.matterInstruction = [];
            this.$refs[`addform_${this.matterType}${this.cid}`][0].resetFields();
            this.$refs[`fireUploadDialog_${this.cid}`][0].clearFiles();
            // this.pageObj.currentPage = 1; // 当前页数
            // }
            if (flag === "close") {
              this.$emit("close", "save");
            }
            // this.initFn();
            this.initFromFn(this.id);
            this.initDataFn(this.cid);
            // this.witnessRecordListFn(); //更新列表 1、添加后刷新；2、复核保存后刷新
            this.$message({
              type: "success",
              message: res.message || "添加成功",
              single: true
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
          // if (flag === "close") {
          //   this.$emit("close", "save");
          // }
          // this.initFn();
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        console.log("this.$parent", this.$parent);
        this.$parent.$parent.loading = false;
        this.submitLoading = false;
      },
      cancelFn() {
        this.visible = false;
      },
      closeFn() {
        this.BaseInfoVisible = false;
        this.keyWord = "";
        this.$emit("close");
      },
      async submitFn() {
        this.loading = true;
        // let witnessSubTaskId = [];
        await this.subtaskReviewFn();
        this.$emit("submit");
      },
      submitSearchFn() {},
      // 审核见证
      async subtaskReviewFn() {
        try {
          this.recordSelected;
          console.log("this.recordSelected", this.recordSelected);
          const recordIds = Object.values(this.recordSelected);
          console.log("recordIds", recordIds);
          // return;
          const p = {
            // witnessTaskId: this.rowData.witnessTaskId,
            recordIds, // 要删除的记录
            witnessSubTaskId: this.rowData.witnessSubTaskId
          };
          // if (p.recordIds.length == 0) {
          //   this.loading = false;
          //   return;
          // }
          const res = await subtaskReview(p);
          if (res.success) {
            this.loading = false;
            // 显示查看见证记录
            this.$message({
              type: "success",
              message: res.message || "操作成功",
              single: true
            });
            // this.detailData = res.data;
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        this.visible = false;
      },
      // 提交
      async subtaskAllocateUserFn() {}
    }
  };
</script>
<style lang="scss" scoped>
  .fire-upload-dialog {
    width: 100%;
    ::v-deep .el-upload {
      width: 100%;
    }
  }
  .witness-matter-warning {
    position: absolute;
    top: 34px;
    left: 0;
    width: 120%;
    font-size: 12px;
    height: 14px;
    line-height: 14px;
    z-index: 9;
    color: $orange;
    overflow: hidden;
    background: #fff;
  }
  .daishenhe-tag {
    position: absolute;
    top: 60px;
    right: 15px;
    i {
      font-size: 70px;
      color: $primary;
    }
  }
  .ui-table th,
  .ui-table td {
    width: 275px;
  }
</style>
